<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="onLoad" finished-text="没有更多了" :immediate-check="false"
        offset="50">
        <ArticleItem v-for="obj in list" :key="obj.art_id" :artObj="obj" @disLikeEV="disLikeFn" @reportEV="reportFn"   @click.native="$router.push(`/article_detail?aid=${obj.art_id}`)"
         />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem.vue'
import { articlesListAPI, articleDislikeAPI, reportArticleAPI } from '@/api'
import Notify from '@/ui/Notify.js'
export default {
  props: {
    channelId: Number// 频道ID
  },
  data () {
    return {
      list: [], // 文章列表数组
      loading: false, // 底部加载状态
      finished: false, // 底部完成状态
      theTime: new Date().getTime(), // 用于分页
      isLoading: false// 顶部加载状态
    }
  },
  components: { ArticleItem },
  computed: {

  },
  created () {
    this.getArticleListFn()
  },
  methods: {
    async getArticleListFn () {
      /*
         list组件触底后, 自动执行load事件和对应onLoad方法, 并把loading值改为true
         异步数据加载完毕, 合并数据, 把loading改为false, 以后再让list自动执行load事件
         异步数据加载完毕, 判断没有数据了, 把finished改为true, 以后再也不出load事件
      */
      const res = await articlesListAPI({ channelId: this.channelId, timestamp: this.theTime })
      this.list = [...this.list, ...res.data.data.results]
      this.theTime = res.data.data.pre_timestamp
      this.loading = false
      if (res.data.data.pre_timestamp === null) {
        this.finished = true
      }
      this.isLoading = false
    },
    /* 不感兴趣 */
    async disLikeFn (id) {
      try {
        await articleDislikeAPI({
          target: id
        })
        Notify({ type: 'success', message: '反馈成功' })
        console.log('成功了')
      } catch (err) {
        console.log('失败了')
      }
    },
    async reportFn (id, value) {
      console.log(id, value)
      try {
        await reportArticleAPI({ artId: id, type: value })
        Notify({ type: 'success', message: '举报成功' })
      } catch (err) {
        console.log(err, '出错')
      }
    },
    /* 下拉触底 */
    onLoad () {
      if (this.list.length === 0) {
        this.loading = false // 第一次上面还是判定触底(触发onLoad方法时loading自动改true)
        // 如果不改回来, 下次触底就不在执行onLoad方法
        return // 如果页面没有数据, 没有高度, 让本次onLoad逻辑代码不往下执行
      }
      if (this.list.length > 0) {
        this.getArticleListFn()
      }
    },
    /* 上拉刷新 */
    /* 把旧数组清空 时间回到系统时间 重新发起一次请求 一定注意, 数据异步刷新完毕, 要关闭isLoading状态 */
    onRefresh () {
      this.list = []
      this.getArticleListFn()
      this.isLoading = false
    }
  }
}
</script>

<style scoped lang="less">
</style>
